package com.tianji.learning.service.impl;

import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author xiaomai
 * @since 2023-10-24
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {

    private final InteractionQuestionMapper interactionQuestionMapper;

    @Override
    public void saveReply(ReplyDTO dto) {
//        获取当前登录用户
        Long userId = UserContext.getUser();
//        保存回答或者评论
        InteractionReply reply = BeanUtils.copyBean(dto, InteractionReply.class);
        this.save(reply);
//        判断是否是回答 dto.answerID是否为空
        InteractionQuestion question = interactionQuestionMapper.selectById(dto.getQuestionId());
        if (dto.getAnswerId() != null) {
            InteractionReply answerInfo = this.getById(dto.getAnswerId());
            answerInfo.setReplyTimes(answerInfo.getReplyTimes() + 1);
            this.updateById(answerInfo);
//        如果不是回答, 累加回答下的评论次数
        } else {
//        如果是回答, 修改问题表最近一次回答id 同时累加问题表回答次数
            question.setLatestAnswerId(reply.getId());
            question.setAnswerTimes(question.getAnswerTimes() + 1);
            interactionQuestionMapper.updateById(question);
        }
        if (dto.getIsStudent()) {
            //        判断是否是学生提交
            question.setStatus(QuestionStatus.UN_CHECK);
        }
        interactionQuestionMapper.updateById(question);
    }
}
